home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1928 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  56 lines

  1. Newsgroups: comp.lang.c
  2. Path: bristol.com!handel!dan
  3. From: dan@bristol.com (J. Daniel Smith)
  4. Subject: Re: Q: realloc->free?
  5. Sender: usenet@bristol.com (USENET News System)
  6. Organization: Bristol Technology Inc.
  7. References: <4df2ud$706@oxy.rust.net> <4dgic7$qin@unix.sri.com>
  8. Message-ID: <dan.821890778@handel>
  9. Date: Wed, 17 Jan 1996 14:59:38 GMT
  10.  
  11. In <4dgic7$qin@unix.sri.com> mklenk@updike.sri.com (Mark Klenk) writes:
  12. >Earl Bennett wrote:
  13. >>
  14. >>realloc() will free the old block.  It is perfectly legal to say
  15. >>
  16. >>  a = realloc(a, newsize);
  17. >>
  18. >>No memory loss should occur from this.
  19. >    Excuse me???  What about if realloc fails?!
  20. >    Then you've lost at least the old number of bytes,
  21. >
  22. >    You should ALWAYS do this instead:
  23. >
  24. >        b = realloc(a, newsize);
  25. >        if (b == NULL) {
  26. >            /* At least we haven't lost 'a'. */
  27. >        }
  28.  
  29. While this is indeed correct, ALWAYS having to write this can make for
  30. ugly code.
  31.  
  32. Let's face it: under normal circumstances, realloc() is not going to
  33. fail; adding code to deal for the extremely rare case can add
  34. significantly to the complexity of the code.  And if realloc() does
  35. fail, there are probably a lot bigger things to worry about than
  36. leaking memory (like the GUI not being able to create a window to tell
  37. you something has went wrong).
  38.  
  39. Yes, the above code is more robust than simply
  40.    a = realloc(a, newsize);
  41. but this marginal increase in robustness (given the chances of
  42. realloc() failing in normal operating conditions) needs to be
  43. evaluated against the added complexity of dealing with the failure.
  44. Yes, the programmer needs to be aware of the fact that realloc() can
  45. fail, but in some cases ALWAYS checking the return value of realloc()
  46. just isn't practical given other constraints.
  47.  
  48. C++ is able to deal with this a bit more elgantly via exceptions.
  49.  
  50.    Dan
  51. -- 
  52. --------------------- message is author's opinion only --------------------
  53. J. Daniel Smith <DanS@bristol.com>              http://www.bristol.com/~dan
  54. Bristol Technology Inc.                        +1 203 438 6969, 438-5013 (FAX)
  55. Ridgefield, Connecticut (USA)                       {info,jobs}@bristol.com
  56.